import React, { useState, useEffect, useMemo, useRef } from 'react';
import { Layout, Tabs, message, Col, Row, Input, Button, Tooltip, Space, Popconfirm, Modal } from 'antd';
import { SearchOutlined, FilterOutlined } from '@ant-design/icons';
import { useIntl, FormattedMessage } from '@umijs/max';
import DynamicToolbar from '@/components/OnlineCollecting/DynamicToolbar';
import ArchiveTable from '@/components/OnlineCollecting/ArchiveTable';
import ArchiveTypeTree from '@/components/OnlineCollecting/ArchiveTypeTree';
import DynamicQueryForm from '@/components/OnlineCollecting/DynamicQueryForm';
import { getMenuButton, getDynamicData, fetchList, getQueryDynamicData, batchDelete } from '@/services/prefiling/onlineCollecting';
import { useAccess } from '@umijs/max';
import styles from './index.less';
import { ArchiveType, ArchiveTabType, TableColumn } from '@/types/prefiling/onlineCollecting';
import { ActionDispatcher } from '@/utils/buttonActions';
import YjsqModal from "./Yjsq";
import FilterModal from "./Filter";


const { Content, Sider } = Layout;

type TableCache = {
  [key: string]: {
    columns: any[];
    loaded: boolean;
  };
};

type TableQueryState = {
  field: string; // 模糊查询词
  exactQuery: Record<string, any>; // 精确查询条件
};

type SearchField = {
  name: string;
  label: string;
  syllableType?: 'input' | 'select' | 'date';
  options?: Array<{ label: string; value: any }>;
};

type FieldType = {
  username?: string;
  password?: string;
  remember?: string;
};

const OnlineCollectingPage: React.FC = () => {
  const intl = useIntl();
  const [menuId, setMenuId] = useState('10088');
  const [fileState, setFileState] = useState('00');
  const [rollState, setRollState] = useState('00');
  const [isDelete, setIsDelete] = useState('0');
  const [relateId, setRelateId] = useState('1');
  const [arrangeDimension, setArrangeDimension] = useState('FILE');
  const [currentType, setCurrentType] = useState<ArchiveType | null>(null);
  const [activeTab, setActiveTab] = useState<ArchiveTabType>('roll');
  const [selectedRows, setSelectedRows] = useState<React.Key[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 20,
    total: 0
  });
  const [loading, setLoading] = useState(false);
  const [tableData, setTableData] = useState<any>({ list: [], total: 0 });
  const [searchFields, setSearchFields] = useState<SearchField[]>([]);
  const [buttonGroups, setButtonGroups] = useState({ file: [], roll: [], fileList: [], unFileList: [] });
  const [actionLoading, setActionLoading] = useState(false);
  const [columnsData, setColumnsData] = useState<Record<string, TableColumn[]>>({});
  const [columnsLoading, setColumnsLoading] = useState(false);
  const [dynamicHeight, setDynamicHeight] = useState(350);
  const [modalyjsq, setModalyjsq] = useState(false)
  const [modalFilter, setModalFilter] = useState(false)
  const queryFormRef = useRef<HTMLDivElement>(null);
  const toolbarRef = useRef<HTMLDivElement>(null);
  const access = useAccess();
  const tableCache = useRef<TableCache>({});

  const [modalParams, setModalParams] = useState({})

  // 为每个Tab维护独立的查询状态
  const [queries, setQueries] = useState<Record<ArchiveTabType, TableQueryState>>({
    roll: { field: '', exactQuery: {} },
    fileList: { field: '', exactQuery: {} },
    unFileList: { field: '', exactQuery: {} },
    file: { field: '', exactQuery: {} }
  });

  //查询条件配置
  const fetchQueryDynamicData = async (tab: ArchiveTabType) => {
    try {
      if (!currentType) return;
      const res = await getQueryDynamicData({
        typeCode: currentType.typeCode,
        templateType: tab === 'roll' ? 'ROLL' : 'FILE',
        fullId: currentType.fullId,
        pageLink: menuId
      });

      if (res.code === 0 && res.data) {
        const convertedFields = convertToSearchFields(res.data);
        setSearchFields(convertedFields);
      }
    } catch (error) {
      message.error('获取查询字段配置失败');
    }
  };

  // 转换动态查询表单数据格式
  const convertToSearchFields = (originalData: any[]): SearchField[] => {
    return originalData.map(item => {
      const field: SearchField = {
        ...item,
        name: item.code,
        label: item.name,
        syllableType: item.syllableType || '1',

      };

      if (item.options && item.options.length > 0) {
        field.options = item.options.map(opt => ({
          label: opt.label || opt.value,
          value: opt.value
        }));
      }

      return field;
    });
  };


  // 处理模糊查询变化
  const handleKeywordChange = (tab: ArchiveTabType, field: string) => {
    setQueries(prev => ({
      ...prev,
      [tab]: {
        ...prev[tab],
        field
      }
    }));
  };

  // 处理精确查询变化
  const handleExactQueryChange = (tab: ArchiveTabType, exactQuery: Record<string, any>) => {
    setQueries(prev => {
      const newQueries = {
        ...prev,
        [tab]: {
          ...prev[tab],
          exactQuery
        }
      };
      return newQueries;
    });

    fetchTableData(tab, {
      current: 1,
      pageSize: pagination.pageSize
    }, exactQuery);
  };


  // 触发查询
  const triggerSearch = (tab: ArchiveTabType) => {
    setPagination(prev => ({ ...prev, current: 1 }));
    fetchTableData(tab);
  };

  const getCacheKey = (type: ArchiveType | null, tab: ArchiveTabType) => {
    return type ? `${type.typeCode}-${tab}` : '';
  };

  // 统一数据获取方法
  const fetchTableData = async (tab: ArchiveTabType, paginationParams?: { current: number; pageSize: number }, exactQueryParams?: any) => {
    if (!currentType) return;
    setLoading(true);
    try {
      let exactQuery = exactQueryParams ? exactQueryParams : queries[tab].exactQuery;
      let field = queries[tab].field;
      const params = {
        typeCode: currentType.typeCode,
        arrangeDimension: tab === 'roll' ? 'ROLL' : 'FILE',
        fullId: currentType.fullId,
        current: paginationParams?.current || pagination.current,
        size: paginationParams?.pageSize || pagination.pageSize,
        fileState,
        rollState,
        isDelete,
        relateId,
        field,      // 模糊查询参数
        ...exactQuery                     // 精确查询参数
      };

      const res = await fetchList(params);

      const newData = {
        list: res.data.records || [],
        total: parseInt(res.data.total) || 0
      };

      const newPagination = {
        current: parseInt(res.data.current) || 1,
        pageSize: parseInt(res.data.size) || 20,
        total: parseInt(res.data.total) || 0
      };

      setTableData(newData);
      setPagination(newPagination);

      const cacheKey = getCacheKey(currentType, tab);
      tableCache.current[cacheKey] = {
        // data: newData,
        columns: tableCache.current[cacheKey]?.columns || [],
        loaded: true
        // pagination: newPagination
      };

      return newData;
    } catch (error) {
      message.error('获取数据失败');
      console.error(error);
      return { list: [], total: 0 };
    } finally {
      setLoading(false);
    }
  };

  // 处理表格变化（分页、排序等）
  const handleTableChange = (params: { pagination?: any; sorter?: any }) => {
    const newPagination = params.pagination || pagination;
    setPagination(newPagination);
    fetchTableData(activeTab, newPagination);
  };

  //获取所有按钮数据
  const fetchButtonColumns = async (): Promise<void> => {
    const response = await getMenuButton({ menuId: menuId });
    if (response.code === 0) {
      const data = response.data;
      let file = data.filter((item) => { return item.modelType == '1' && access.hasPerms(item.permission) });
      let roll = data.filter((item) => { return item.modelType == '2' && access.hasPerms(item.permission) });
      let fileList = data.filter((item) => { return item.modelType == '3' && access.hasPerms(item.permission) });
      let unFileList = data.filter((item) => { return item.modelType == '4' && access.hasPerms(item.permission) });
      setButtonGroups({ file: file, roll: roll, fileList: fileList, unFileList: unFileList });
    } else {
      message.error(response.data.message);
    }
  };

  //计算动态高度的函数
  const calculateDynamicHeight = () => {
    let height = 271; // 基础高度

    // 获取查询表单高度
    if (queryFormRef.current) {
      height += queryFormRef.current.offsetHeight;
    }

    // 获取工具栏高度
    if (toolbarRef.current) {
      height += toolbarRef.current.offsetHeight;
    }

    // 当有选项卡
    if (activeTab != 'file') {
      height += 55;
    }
    setDynamicHeight(height);
  };

  const yjsqOk = () => {

  }
  const yjsqCancel = () => {

  }

  useEffect(() => {
    calculateDynamicHeight();
  }, [activeTab, searchFields, buttonGroups]);

  useEffect(() => {
    fetchButtonColumns();
  }, []);

  useEffect(() => {
    ActionDispatcher.register({
      // 注册的action处理函数
      prefiling_oc_yjsq: async (params) => {
        setModalyjsq(true)
        console.log('打开弹窗')
        setModalParams(params)
      }
    });

    return () => {
      ActionDispatcher.reset();
    };
  }, [activeTab, queries]);

  useEffect(() => {
    ActionDispatcher.setLoadingHandler(setActionLoading);
    return () => {
      ActionDispatcher.setLoadingHandler(() => { });
    };
  }, []);

  useEffect(() => {
    ActionDispatcher.setRefreshHandler(() => {
      setSelectedRows([]);
      triggerSearch(activeTab);
    });
    return () => {
      ActionDispatcher.clearRefreshHandler();
    };
  }, [activeTab, queries]);

  useEffect(() => {
    if (currentType) {
      loadTabData(currentType, activeTab);
    }
  }, [currentType?.typeCode]);

  // 获取表头数据的方法
  const fetchColumns = async (typeCode: string, tab: ArchiveTabType): Promise<TableColumn[]> => {
    const cacheKey = `${typeCode}-${tab}`;
    setColumnsLoading(true);

    try {
      const res = await getDynamicData({
        typeCode,
        templateType: tab === 'roll' ? 'ROLL' : 'FILE',
        fullId: currentType?.fullId,
        pageLink: menuId
      });

      // 转换表头数据为TableColumn格式
      const convertedColumns = convertToAntdColumns(res.data);
      setColumnsData(prev => ({ ...prev, [cacheKey]: convertedColumns }));

      tableCache.current[cacheKey] = {
        columns: convertedColumns,
        loaded: true
      };

      return convertedColumns;
    } catch (error) {
      console.error('获取列数据失败:', error);
      message.error('获取列数据失败');
      return [];
    } finally {
      setColumnsLoading(false);
    }
  };

  // 转换表头数据的方法
  const convertToAntdColumns = (originalData: any[]): TableColumn[] => {
    const defaultOptions = {
      keepOrder: true,
      showActionColumn: true,
    };

    let columns = originalData.map(item => {
      const width = item.labelWidth && item.labelWidth.trim() !== ""
        ? parseInt(item.labelWidth)
        : 150;

      const column: TableColumn = {
        title: item.name,
        dataIndex: item.code,
        key: item.code,
        width: width,
        minWidth: width,
        align: 'left',
        render: (text: any) => (
          <Tooltip
            title={text}
            placement="topLeft"
            mouseEnterDelay={0.3}
            styles={{
              popup: { maxWidth: 600 }
            }}
          >
            <div style={{
              width: width - 16,
              whiteSpace: 'nowrap',
              overflow: 'hidden',
              textOverflow: 'ellipsis',
            }}>
              {text}
            </div>
          </Tooltip>
        )
      };
      return column;
    });

    // 添加操作列
    if (defaultOptions.showActionColumn) {
      columns.push(
        {
          title: '操作',
          key: 'action',
          width: 130,
          fixed: 'right',
          render: (_, record) => (
            <Space size="middle">
              <a onClick={() => handleEdit(record)}>编辑</a>
              <Popconfirm
                title="确认删除吗?"
                description={`确定删除该条档案信息吗？`}
                onConfirm={() => handleRemove(record)}
                okText="确认"
                cancelText="取消"
              >
                <Button danger type="link">删除</Button>
              </Popconfirm>
            </Space>
          ),
        },
        {
          title: '查看',
          key: 'view',
          width: 130,
          fixed: 'right',
          render: (_, record) => (
            <Space size="middle">
              {/* <a onClick={() => handleFileView(record)}>附件</a>
              <a onClick={() => handleDetail(record)}>详情</a> */}
            </Space>
          ),
        }
      );
    }

    return columns;
  };

  //表格列编辑
  const handleEdit = (record: any) => {
    console.log(record)
    window.openGlobalTab(
      'onlineCollecting-edit',
      '在线采集编辑',
      '/prefiling/onlineCollecting/add',
      {
        typeCode: record.typeCode,
        fileState,
        arrangeDimension: currentType.arrangeDimension,
        fullId: currentType.fullId,
        pageLink: menuId,
        queryType: menuId == '10558' ? 2 : 1,
        id: record.id,
      }
    );
  };

  //表格列删除记录
  const handleRemove = async (record: any) => {
    console.log(record)
    console.log(currentType)
    var response = await batchDelete({
      id: record.id,
      typeCode: record.typeCode,
      arrangeDimension: currentType.arrangeDimension,
      fullId: currentType.fullId
    })
    if (response.code == 0) {
      message.info("删除成功")
      triggerSearch(activeTab);
    } else {
      message.warning(response.msg)
    }
  }


  const handleTypeSelect = (typeNode: ArchiveType) => {
    const newArrangeDimension = typeNode.arrangeDimension;
    const newActiveTab = typeNode.arrangeDimension === 'ROLL' ? 'roll' : 'file';
    // 重置缓存状态
    const cacheKey = getCacheKey(currentType, activeTab);
    if (cacheKey && tableCache.current[cacheKey]) {
      tableCache.current[cacheKey].loaded = false;
    }
    if (typeNode.arrangeDimension == "ROLL") {
      if (tableCache.current[typeNode.typeCode + '-fileList']) {
        tableCache.current[typeNode.typeCode + '-fileList'].loaded = false;
      }
      if (tableCache.current[typeNode.typeCode + '-unFileList']) {
        tableCache.current[typeNode.typeCode + '-unFileList'].loaded = false;
      }
    }
    setQueries({
      roll: { field: '', exactQuery: {} },
      fileList: { field: '', exactQuery: {} },
      unFileList: { field: '', exactQuery: {} },
      file: { field: '', exactQuery: {} }
    });
    console.log('typeNode=',typeNode);
    
    setCurrentType(typeNode);
    setArrangeDimension(newArrangeDimension);
    setActiveTab(newActiveTab);
  };

  // 处理选项卡切换
  const handleTabChange = async (key: string) => {
    if (!currentType) return;

    const newTab = key as ArchiveTabType;
    setActiveTab(newTab);

    if (!currentType) return;

    const cacheKey = getCacheKey(currentType, key as ArchiveTabType);

    if (tableCache.current[cacheKey] && tableCache.current[cacheKey].loaded) {

    } else {
      await loadTabData(currentType, newTab);

    }
  };

  // 加载选项卡数据
  const loadTabData = async (typeNode: ArchiveType, tab: ArchiveTabType) => {
    const typeCode = typeNode.typeCode;
    const cacheKey = `${typeCode}-${tab}`;
    try {
      // 并行加载表头和表格数据
      await Promise.all([
        !columnsData[cacheKey] && fetchColumns(typeCode, tab),
        fetchTableData(tab),
        fetchQueryDynamicData(tab)
      ]);
    } catch (error) {
      console.error('加载选项卡数据失败:', error);
      message.error('加载数据失败');
    }
  };


  const renderTabContent = (tab: ArchiveTabType) => {
    const cacheKey = currentType ? `${currentType.typeCode}-${tab}` : '';
    const columns = columnsData[cacheKey] || [];
    const data = tableData.list || [];


    return (
      <>
        <Row>
          <Col span={24}>
            <div ref={queryFormRef}>
              <DynamicQueryForm
                type={tab}
                fields={searchFields}
                initialValues={queries[tab].exactQuery}
                onSearch={(values) => {
                  console.log(values)
                  queries[tab].field = "";
                  handleExactQueryChange(tab, values);
                }}
                onReset={() => {
                  handleExactQueryChange(tab, {});
                }}
              />
            </div>
          </Col>
        </Row>
        <Row
          ref={toolbarRef}
          gutter={16}
          style={{
            display: 'flex',       // 启用 Flex 布局
            flexWrap: 'nowrap',    // 禁止整体换行（保证右侧搜索框不换行）
            alignItems: 'flex-start', // 顶部对齐
            marginBottom: 16
          }}>
          <Col xs={24} md={18}  >
            <DynamicToolbar
              type={tab}
              selectedRows={selectedRows}
              buttons={buttonGroups[tab]}
              currentType={currentType}
              loading={actionLoading}
              menuId={menuId}
              fileState={fileState}
            />
          </Col>
          <Col xs={24} md={6}>
            <div style={{ marginBottom: 16, display: 'flex' }}>
              <Input.Search
                placeholder="请输入关键词模糊查询"
                value={queries[tab].field}
                onChange={(e) => handleKeywordChange(tab, e.target.value)}
                onSearch={() => {
                  queries[tab].exactQuery = {};
                  triggerSearch(tab)
                }}
                enterButton={<SearchOutlined />}
              />
              <Button
                icon={<FilterOutlined />}
                style={{ marginLeft: 8 }}
                onClick={()=>{setModalFilter(true)}}
              />
            </div>
          </Col>
        </Row>
        <ArchiveTable
          type={tab}
          columns={columns}
          data={{ list: data, total: tableData.total }}
          loading={loading || columnsLoading}
          selectedRows={selectedRows}
          onSelectChange={setSelectedRows}
          onTableChange={handleTableChange}
          pagination={pagination}
          dynamicHeight={dynamicHeight}
        />
        {modalyjsq&&<YjsqModal open={modalyjsq} setOpen={setModalyjsq} modalParams={modalParams}/>}
        {modalFilter&&<FilterModal open={modalFilter} setOpen={setModalFilter} modalParams={modalParams}/>}
      </>
    );
  };

  // 渲染ROLL类型的Tabs
  const rollTabsItems = [
    {
      key: 'roll',
      label: '档案案卷库',
      children: renderTabContent('roll')
    },
    {
      key: 'fileList',
      label: '卷内文件库',
      children: renderTabContent('fileList')
    },
    {
      key: 'unFileList',
      label: '未整理文件',
      children: renderTabContent('unFileList')
    }
  ];

  return (
    <Layout className={styles.layoutConent}>
      <Sider width={300} className={styles.sider} collapsible collapsedWidth={15}>
        <ArchiveTypeTree menuId={menuId} onSelect={handleTypeSelect} />
      </Sider>
      <Content className={styles.content}>
        {currentType?.arrangeDimension === 'ROLL' ? (
          <Tabs
            activeKey={activeTab}
            onChange={handleTabChange}
            className={styles.tabs}
            items={rollTabsItems}
          />
        ) : (
          renderTabContent('file')
        )}
      </Content>
    </Layout>
  );
};

export default OnlineCollectingPage;